package com.campus.client.view;

import com.campus.client.controller.StudentApprovalController;
import com.campus.client.net.ClientConnector;
import com.campus.common.message.StudentAccountManagementResponse;
import com.campus.common.vo.Student;
import com.campus.common.vo.StudentRequest;
import com.campus.common.vo.User;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.geometry.Insets;
import javafx.geometry.Pos;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class StudentApprovalFrame {
    private TableView<StudentRequest> requestTable;
    private Button backBtn;
    private User user = new User();
    private ClientConnector connector;
    private StudentApprovalController controller;

    public User getUser() {
        return user;
    }

    public void setUser(String Id, String password, String role) {
        this.user.setId(Id);
        this.user.setPassword(password);
        this.user.setRole(role);
    }

    public void start(Stage primaryStage) throws Exception {
        BorderPane root = new BorderPane();
        root.setPadding(new Insets(10));
        root.getStyleClass().add("main-container");

        connector=new ClientConnector("172.20.10.2", 8888);
        controller=new  StudentApprovalController(connector);

        // 顶部标题栏
        HBox headerBox = new HBox();
        headerBox.getStyleClass().add("header-box");
        headerBox.setAlignment(Pos.CENTER_LEFT);
        headerBox.setPadding(new Insets(10, 15, 10, 15));

        Label titleLabel = new Label("学生信息修改审批 - 管理员版");
        titleLabel.getStyleClass().add("header-title");

        Region spacer = new Region();
        HBox.setHgrow(spacer, Priority.ALWAYS);

        backBtn = createStyledButton("返回");
        backBtn.getStyleClass().add("secondary-button");
        backBtn.setOnAction(e -> back());

        headerBox.getChildren().addAll(titleLabel, spacer, backBtn);
        root.setTop(headerBox);

        // 内容区域
        VBox contentBox = new VBox();
        contentBox.getStyleClass().add("content-box");
        contentBox.setPadding(new Insets(15));

        // 创建表格
        requestTable = new TableView<>();
        requestTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
        setupTableColumns();

        // 添加表格到滚动面板
        ScrollPane scrollPane = new ScrollPane(requestTable);
        scrollPane.setFitToWidth(true);
        scrollPane.setFitToHeight(true);
        scrollPane.getStyleClass().add("scroll-pane");

        contentBox.getChildren().add(scrollPane);
        root.setCenter(contentBox);

        // 加载模拟数据
        loadAllRequests();

        Scene scene = new Scene(root, 1000, 600);
        scene.getStylesheets().add(getClass().getResource("/css/style.css").toExternalForm());
        primaryStage.setTitle("学生信息修改审批 - 管理员版");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    // 设置表格列
    private void setupTableColumns() {
        // 学号列
        TableColumn<StudentRequest, String> idCol = new TableColumn<>("学号");
        idCol.setCellValueFactory(cellData -> new javafx.beans.property.SimpleStringProperty(cellData.getValue().getStudentId()));
        idCol.setMinWidth(100);

        // 旧联系方式列
        TableColumn<StudentRequest, String> oldContactCol = new TableColumn<>("旧联系方式");
        oldContactCol.setCellValueFactory(cellData -> new javafx.beans.property.SimpleStringProperty(cellData.getValue().getOldContactInfo()));
        oldContactCol.setMinWidth(150);

        // 新联系方式列
        TableColumn<StudentRequest, String> newContactCol = new TableColumn<>("新联系方式");
        newContactCol.setCellValueFactory(cellData -> new javafx.beans.property.SimpleStringProperty(cellData.getValue().getContactInfo()));
        newContactCol.setMinWidth(150);

        // 申请时间列
        TableColumn<StudentRequest, String> timeCol = new TableColumn<>("申请时间");
        timeCol.setCellValueFactory(cellData -> new javafx.beans.property.SimpleStringProperty(cellData.getValue().getTime()));
        timeCol.setMinWidth(150);

        // 操作列
        TableColumn<StudentRequest, Void> actionCol = new TableColumn<>("操作");
        actionCol.setMinWidth(200);
        actionCol.setCellFactory(new Callback<TableColumn<StudentRequest, Void>, TableCell<StudentRequest, Void>>() {
            @Override
            public TableCell<StudentRequest, Void> call(final TableColumn<StudentRequest, Void> param) {
                return new TableCell<StudentRequest, Void>() {
                    private final Button approveBtn = createStyledButton("批准");
                    private final Button rejectBtn = createStyledButton("驳回");
                    private final HBox pane = new HBox(10, approveBtn, rejectBtn);

                    {
                        pane.setAlignment(Pos.CENTER);
                        approveBtn.getStyleClass().add("primary-button");
                        rejectBtn.getStyleClass().add("danger-button");

                        // 按钮事件处理（暂不实现具体功能）
                        approveBtn.setOnAction(event -> {
                            StudentRequest request = getTableView().getItems().get(getIndex());
                            try {
                                boolean success=controller.upDateStudent(request.getStudentId(), request.getContactInfo());
                                controller.deleteRequest(request.getStudentId(), request.getContactInfo());
                                if(success){
                                    showAlert("请求处理","已批准！", Alert.AlertType.INFORMATION);
                                    loadAllRequests();
                                }
                                else{
                                    showAlert("请求处理","批准失败！", Alert.AlertType.ERROR);
                                }
                            } catch (ClassNotFoundException e) {
                                throw new RuntimeException(e);
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                            System.out.println("批准请求: " + request.getStudentId());
                            // 这里可以添加批准逻辑
                        });

                        rejectBtn.setOnAction(event -> {
                            StudentRequest request = getTableView().getItems().get(getIndex());
                            try {
                                boolean success=controller.deleteRequest(request.getStudentId(), request.getContactInfo());
                                if(success){
                                    showAlert("请求处理","已驳回！", Alert.AlertType.INFORMATION);
                                    loadAllRequests();
                                }
                                else{
                                    showAlert("请求处理","驳回失败！", Alert.AlertType.ERROR);
                                }
                            } catch (ClassNotFoundException e) {
                                throw new RuntimeException(e);
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                            System.out.println("驳回请求: " + request.getStudentId());
                            // 这里可以添加驳回逻辑
                        });
                    }

                    @Override
                    protected void updateItem(Void item, boolean empty) {
                        super.updateItem(item, empty);
                        if (empty) {
                            setGraphic(null);
                        } else {
                            setGraphic(pane);
                        }
                    }
                };
            }
        });

        requestTable.getColumns().addAll(idCol, oldContactCol, newContactCol, timeCol, actionCol);
    }

    // 统一按钮创建方法
    private Button createStyledButton(String text) {
        Button button = new Button(text);
        button.getStyleClass().add("styled-button");
        return button;
    }

    // 统一提示对话框
    private void showAlert(String title, String message, Alert.AlertType type) {
        Alert alert = new Alert(type, message, ButtonType.OK);
        alert.setHeaderText(title);
        alert.showAndWait();
    }

    private void loadAllRequests() {
        try {
            List<StudentRequest> requests = controller.loadAllRequest();
            requestTable.getItems().setAll(requests);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void back() {
        // 获取当前窗口的Stage
        Stage currentStage = (Stage) backBtn.getScene().getWindow();
        currentStage.close();

        // 返回账号管理界面
        try {
            StudentAccountManagementFrame accountManagementFrame = new StudentAccountManagementFrame();
            accountManagementFrame.setUser(user.getId(), user.getPassword(), user.getRole());
            accountManagementFrame.start(new Stage());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

